import React, { Component, ReactNode } from "react"

// 定义 props 类型
interface ErrorBoundaryProps {
    fallback: ReactNode
    children: ReactNode // 允许传递子组件
}

// 定义 state 类型
interface ErrorBoundaryState {
    hasError: boolean
}

class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
    state: ErrorBoundaryState = { hasError: false }
    // 添加 PropTypes 校验（运行时检查）

    static getDerivedStateFromError(): ErrorBoundaryState {
        return { hasError: true }
    }

    componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
        // componentDidCatch 可以捕获render函数的错误
        console.log(error, errorInfo)

        // 上报错误
    }

    render() {
        return this.state.hasError ? this.props.fallback : this.props.children
    }
}

export default ErrorBoundary
